package com.zim.aliot.util;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.zim.aliot.constant.RedisConstant;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class RedisLockUtils {
	@Autowired
	private StringRedisTemplate redisTemplate;
	
	public boolean lock(String key,String value) {
		if(redisTemplate.opsForValue().setIfAbsent(key, value)) {
		    redisTemplate.boundValueOps(key).expire(RedisConstant.EXPIRE, TimeUnit.SECONDS);
			return true;
		}
		
		String currentValue = redisTemplate.opsForValue().get(key);
		
		if(!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
			
			String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
			
			if(!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
			    redisTemplate.boundValueOps(key).expire(RedisConstant.EXPIRE, TimeUnit.SECONDS);
				return true;
			}
		}
		
		return false;
	}
	
	public void unlock(String key,String value) {
		try {
			String currentValue =  redisTemplate.opsForValue().get(key);
			if(!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
				redisTemplate.opsForValue().getOperations().delete(key);
			}
		} catch (Exception e) {
			log.error("解锁异常:{}",e);
		}
		
	}
}
